package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;

import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CateGoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        /*
        - 根据当前分类的ID，查询该分类下是否存在菜品，如果存在，则提示错误信息
        - 根据当前分类的ID，查询该分类下是否存在套餐，如果存在，则提示错误信息
        - 执行正常的删除分类操作
         */
        //1.查看菜品分类中是否包含菜品
        LambdaQueryWrapper<Dish> dishlqw = new LambdaQueryWrapper<>();
        dishlqw.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishlqw);
        if (dishCount > 0) {//此时说明包含菜品，抛出异常
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        //2.查看套餐分类里面是否包含套餐
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealLqw);
        if (setmealCount>0){
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        //3.执行物理删除
        super.removeById(id);
    }
}
